import { queryOrders, getOrderById, queryProducts, queryDrawers, queryLinkmans, queryAddresses, queryBuyers, updateOrder, updateOrderTgApproval,
        querySupplyGoods, queryOrderCost, deleteOrderCost, approvalOrder, applyOrderCost, confirmCost, addOrderCost, returnOrder, geneateCD, queryTgManagers
} from "../../services/order/declareApproval";

import { message } from "antd";
const productAddTempIdPrefix = "productAddTempIdPrefix_";
const R = require('ramda');
export default {
    namespace: 'declareApproval',
    state: {
        page: {
            page: 1,
            size: 10,
            totalRow: 0,
            totalPage: 0
        },
        productPage: {
            page: 1,
            size: 10,
            totalRow: 0,
            totalPage: 0
        },
        costPage: {
            page: 1,
            size: 10,
            totalRow: 0,
            totalPage: 0
        },
        list: [],
        allproducts: [],
        supplyGoodsList: [],
        drawerList: [],
        linkmanList: [],
        addressList: [],
        buyerList: [],
        costList: [],
        dataSource: {},
        orderTgApproval: {},
        customer: {},
        goodsAddress: {},
        linkMan: {},
        buyer:{},
        settlement: {},
        tradeCountry: {},
        countryCD: {},
        placeClearance: {},
        orderCharges: {},
        kindPackage: {},
        supervision: {},
        natureExemption: {},
        priceItem: {},
        tgManagerList: [],
        lesseeInfo: {},
        statistics: []
    },
    reducers: {
        /**
         * 设置数据列表
         *
         * @param state
         * @param action
         */
        setOrderManageList(state, { payload }) {
            return { ...state, list: payload.list, page: payload.page }
        },
        /**
         * 设置产品数据列表
         *
         * @param state
         * @param action
         */
        setProductList(state, { payload }) {
            return { ...state, allproducts: payload.productList, productPage: payload.productPage }
        },
        /**
         * 设置费用列表
         *
         * @param state
         * @param action
         */
        setCostList(state, { payload }) {
            return { ...state, costList: payload.costList, costPage: payload.costPage }
        },
        /**
         * 设置开票人数据列表
         *
         * @param state
         * @param action
         */
        setDrawerList(state, { payload }) {
            return { ...state, drawerList: payload.drawerList}
        },
        /**
         * 设置联系人数据列表
         *
         * @param state
         * @param action
         */
        setLinkmanList(state, { payload }) {
            return { ...state, linkmanList: payload.linkmanList}
        },
        /**
         * 设置境内货源地列表
         *
         * @param state
         * @param action
         */
        setSupplyGoodsList(state, { payload }) {
            return { ...state, supplyGoodsList: payload.supplyGoodsList}
        },
        /**
         * 设置货物存放地址数据列表
         *
         * @param state
         * @param action
         */
        setAddressList(state, { payload }) {
            return { ...state, addressList: payload.addressList}
        },
        /**
         * 设置货物存放地址数据列表
         *
         * @param state
         * @param action
         */
        setBuyerList(state, { payload }) {
            return { ...state, buyerList: payload.buyerList}
        },
        /**
         * 设置通关专员列表
         *
         * @param state
         * @param action
         */
        setTgManagerList(state, { payload }) {
            return { ...state, tgManagerList: payload.tgManagerList}
        },
        refreshState(state, { payload }) {
            return {...state, ...payload}
        }
    },
    effects: {
        /**
         * 分页查询订单
         *
         * @param call
         * @param put
         * @param select
         */
        *queryOrderManageList({payload}, { call, put, select }) {
            let page = yield select(state => state.declareApproval.page);
            page = R.isNil(payload) || R.isNil(payload.page) ? page : payload.page;
            const res = yield call(queryOrders, {
                    applyFlag: true, 
                    cstName: R.isNil(payload) || R.isNil(payload.cstName) ? "" : payload.cstName, 
                    orderNo: R.isNil(payload) || R.isNil(payload.orderNo) ? "" : payload.orderNo, 
                    contractNo: R.isNil(payload) || R.isNil(payload.contractNo) ? "" : payload.contractNo, 
                    declarationType: R.isNil(payload) || R.isNil(payload.declarationType) ? "" : payload.declarationType, 
                    status: R.isNil(payload) || R.isNil(payload.status) ? "" : payload.status,
                    beginTime: payload.beginTime,
                    endTime: payload.endTime,
                    page: page})
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                yield put({
                    type: 'refreshState',
                    payload: {
                        list: R.isNil(content.list) ? [] : content.list,
                        statistics: content.statistics ? content.statistics : [],
                        page: R.isNil(content.page) ? page : content.page
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 查询开票人下拉列表
         *
         * @param call
         * @param put
         * @param select
         */
        *queryDrawerList({payload }, { call, put, select }) {
            const res = yield call(queryDrawers, { cstId:payload.cstId, status: "4" });
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                yield put({
                    type: 'setDrawerList',
                    payload: {
                        drawerList: R.isNil(content) ? [] : content,
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 查询联系人
         *
         * @param call
         * @param put
         * @param select
         */
        *queryLinkmanList({payload}, { call, put, select }) {
            const res = yield call(queryLinkmans, { cstId:payload.cstId/*, status: "1"*/ });
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                yield put({
                    type: 'setLinkmanList',
                    payload: {
                        linkmanList: R.isNil(content) ? [] : content,
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 查询货物存放地址
         *
         * @param call
         * @param put
         * @param select
         */
        *queryAddressList({payload}, { call, put, select }) {
            const res = yield call(queryAddresses, { cstId:payload.cstId/*, status: "1"*/ });
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                yield put({
                    type: 'setAddressList',
                    payload: {
                        addressList: R.isNil(content) ? [] : content,
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },
        /**
         * 查询境外买家下拉
         *
         * @param call
         * @param put
         * @param select
         */
        *queryBuyerList({payload}, { call, put, select }) {
            const res = yield call(queryBuyers, { cstId:payload.cstId/*, status: "1"*/ });
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                yield put({
                    type: 'setBuyerList',
                    payload: {
                        buyerList: R.isNil(content) ? [] : content,
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 根据客户查询订单境内货源地
         *
         * @param call
         * @param put
         * @param select
         */
        *querySupplyGoods({payload }, { call, put, select }) {
            const res = yield call(querySupplyGoods, { cstId:payload.cstId});
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                yield put({
                    type: 'setSupplyGoodsList',
                    payload: {
                        supplyGoodsList: R.isNil(content) ? [] : content,
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 根据id获取订单详情
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *getOrderById({ payload }, { call, put, select }) {
            const res = yield call(getOrderById, { id: payload.id });
            if (res.data.resultCode === "ok") {
                let data = res.data.content;
                let order = data.order;
                let orderProductDetails = R.isNil(data.orderProductDetails) || R.isEmpty(data.orderProductDetails) ? [] : data.orderProductDetails;
                R.map((row)=>{row.key = row.id},orderProductDetails);
                order.orderProductDetails = orderProductDetails;
                yield put({
                    type: "refreshState",
                    payload: {
                        dataSource: order,
                        customer: R.isNil(data.customer) ? {} : data.customer,
                        goodsAddress: R.isNil(data.goodsAddress) ? {} : data.goodsAddress,
                        linkMan: R.isNil(data.linkMan) ? {} : data.linkMan,
                        buyer: R.isNil(data.buyer) ? {} : data.buyer,
                        settlement: R.isNil(data.settlement) ? {} : data.settlement,
                        tradeCountry: R.isNil(data.tradeCountry) ? {} : data.tradeCountry,
                        countryCD: R.isNil(data.countryCD) ? {} : data.countryCD,
                        placeClearance: R.isNil(data.placeClearance) ? {} : data.placeClearance,
                        orderCharges: R.isNil(data.orderCharges) ? [] : data.orderCharges,
                        kindPackage: R.isNil(data.kindPackage) ? {} : data.kindPackage,
                        supervision: R.isNil(data.supervision) ? {} : data.supervision,
                        natureExemption: R.isNil(data.natureExemption) ? {} : data.natureExemption,
                        priceItem: R.isNil(data.priceItem) ? {} : data.priceItem,
                        orderTgApproval: R.isNil(data.orderTgApproval) ? {} : data.orderTgApproval,
                        lesseeInfo:R.isNil(data.lesseeInfo) ? {} :data.lesseeInfo,
                        declaration: data.declaration ? data.declaration : {}
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }

        },

        /**
         * 更新订单
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *updateOrder({payload}, { call, put, select }) {
            const dataSource = payload.dataSource;
            let orderProductDetails = [];
            R.map((product)=>{
                let temp = R.omit(['key', 'createtime', 'creator', 'status', 'updater', 'updatetime'])(product);
                if(R.contains(productAddTempIdPrefix)(temp.id)){
                    temp.id = "";//去掉新增临时定义的id
                }
                orderProductDetails = R.concat(orderProductDetails, [temp]);
            }, R.isNil(dataSource.orderProductDetails) ? [] : dataSource.orderProductDetails) //去掉key
            const res = yield call(updateOrder, {order: dataSource});
            if (res.data.resultCode === "ok") {
                message.info("修改成功！");
                if(payload.onSuccess)payload.onSuccess();
                yield put({
                    type: 'queryOrderManageList',
                    payload: R.isNil(payload.searchConditions) ? {} : payload.searchConditions
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 分页查询费用列表
         *
         * @param call
         * @param put
         * @param select
         */
        *queryOrderCost({payload }, { call, put, select }) {
            const res = yield call(queryOrderCost, { orderId: payload.id, status: payload.status, costPage: payload.costPage });
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                let costList = R.isNil(content.list) ? [] : content.list;
                yield put({
                    type: 'setCostList',
                    payload: {
                        costList: costList,
                        costPage: R.isNil(content.page) ? payload.costPage : content.page
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 删除费用
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *deleteOrderCost({ payload }, { call, put, select }) {
            const res = yield call(deleteOrderCost, { id: payload.id });
            if (res.data.resultCode === "ok") {
                message.info("删除成功！");
                yield put({
                    type: "queryOrderCost",
                    payload: R.isNil(payload.searchConditions) ? {} : payload.searchConditions
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 添加费用
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *addOrderCost({payload}, { call, put, select }) {
            const res = yield call(addOrderCost, {orderId: payload.id, cost: payload.cost})
            if (res.data.resultCode === "ok") {
                message.info("添加费用成功！");
                yield put({
                    type: 'queryOrderCost',
                    payload: R.isNil(payload.searchConditions) ? {} : payload.searchConditions
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 申报/审批 费用
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *applyOrderCost({ payload }, { call, put, select }) {
            const res = yield call(applyOrderCost, { cost: payload.cost });
            if (res.data.resultCode === "ok") {
                message.info("审批成功！");
                yield put({
                    type: "queryOrderCost",
                    payload: R.isNil(payload.searchConditions) ? {} : payload.searchConditions
                });
            } else {
                message.error(res.data.errMessage);
            }
        },


        /**
         * 确认费用收齐
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *confirmCost({ payload }, { call, put, select }) {
            const res = yield call(confirmCost, { id: payload.id, status: payload.status });
            if (res.data.resultCode === "ok") {
                message.info(payload.status === "1" ? "通关费用确认申报完毕!" : "跟单费用确认申报完毕!");
                yield put({
                    type: "queryOrderManageList",
                    payload: R.isNil(payload.searchConditions) ? {} : payload.searchConditions
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 通关-退回订单
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *returnOrder({ payload }, { call, put, select }) {
            const res = yield call(returnOrder, { id: payload.id, gobackreason: payload.gobackreason });
            if (res.data.resultCode === "ok") {
                message.info("订单退回成功!");
                yield put({
                    type: "queryOrderManageList",
                    payload: R.isNil(payload.searchConditions) ? {} : payload.searchConditions
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 通关受理提交
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *approvalOrder({payload}, { call, put, select }) {
            const approvalSource = payload.approvalSource;
            const res = yield call(approvalOrder, {approvalOrder: approvalSource});
            if (res.data.resultCode === "ok") {
                message.info("通关受理成功！");
                yield put({
                    type: 'queryOrderManageList',
                    payload: R.isNil(payload.searchConditions) ? {} : payload.searchConditions
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 通关-生成报关资料
         *
         * @param id
         * @param orderTgApproval 通关信息
         */
        *geneateCD({payload}, { call, put, select }) {
            const res = yield call(geneateCD, {...R.omit(['onSuccess'])(payload)});
            if (res.data.resultCode === "ok") {
                debugger;
                message.info("提交通关易成功！");
                if (payload.onSuccess) payload.onSuccess();
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 修改通关信息
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *updateOrderTgApproval({payload}, { call, put, select }) {
            const res = yield call(updateOrderTgApproval, {orderTgApproval: payload.orderTgApproval})
            if (res.data.resultCode === "ok") {
                message.info("通关信息成功！");
                if(payload.onSuccess)payload.onSuccess();
                yield put({
                    type: 'queryOrderManageList',
                    payload: R.isNil(payload.searchConditions) ? {} : payload.searchConditions
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         * 查询通关专员
         *
         * @param call
         * @param put
         * @param select
         */
        *queryTgManagers({payload}, { call, put, select }) {
            const res = yield call(queryTgManagers);
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                yield put({
                    type: 'setTgManagerList',
                    payload: {
                        tgManagerList: R.isNil(content) ? [] : content,
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

    },
/*     subscriptions: {
        setup({ history, dispatch }) {
            return history.listen(({ pathname }) => {
                dispatch({
                    type: 'queryOrderManageList'
                });
            });
        }
    } */
};